/**
 * name:        商品详情
 * author:      wuwq & lyj
 * Time:        18/01/31
 * Copyright:   chinadangmai.com
 */
$(function(){
    // 左边显示加载中
    $('#left').append('<p class="none">加载中....</p>')
    var new_arr=''
    if($.cookie('no_login')!=''&&$.cookie('no_login')!=null){
        new_arr=$.cookie('no_login')
        $('.shopping_cart em').addClass('red')
    } 
    var url=window.location.search;
    var id = url.substring(url.lastIndexOf('=')+1, url.length);
    $('#goodsId').val(id)
    if($.cookie('user')!=''&&$.cookie('user')!=null){
        strs=$.cookie('user').split(",")
        var token=''
        for(var i in strs){
            token=strs[6]
        }
        // $('.buy_now_btn').attr('href','/cart/pay_commit.html?goodsid='+id);
    } 

    var data={goodsId:id,token:token}
    $.ajax({
        url:new_url+'shop/goods/getGoodsDetail',
        type:'post',
        data:data,
        dataType:'json',
        success:function(e){ 
            var r_wrap_bg = $('#r_wrap_bg').html();
            var norms_bg=$('#norms_bg').html();
            var norms_spec_bg=$('#norms_spec_bg').html();
            var category_bg=$('#category_bg').html()
            var left_bg=$('#left_bg').html()
            var wrapper_bg=$('#wrapper_bg').html()
            var custom=$('#custom').html()
            // code==4002 商品已下架
            if(e.code=='4002'){
                $('.popover').remove();
                window.location.href='/src/goods/goods_detail_no.html'
            }
            if(e.code=='0'||e.code=='4001'){
                    //leftRecommand
                        if(e.data.leftRecommand.length>'0'){
                            for(var le=0; le<e.data.leftRecommand.length; le++){
                                var left=template(
                                    left_bg,{
                                        list:[{
                                            leftGdId:e.data.leftRecommand[le].leftGoodsId, //左边商品id
                                            leftGdImage:e.data.leftRecommand[le].image, //商品图片
                                            leftGdMarketPrice:e.data.leftRecommand[le].marketPrice, //价格
                                            leftGdName:e.data.leftRecommand[le].name,//商品名字
                                            leftGdPrice:e.data.leftRecommand[le].unitPrice //商品库存
                                        }]
                                    }
                                )
                                $('#left').append(left)
                                // 移除加载中
                                $('.none').hide();
                            }
                            // 商品详情显示
                            $('.goods_content').append('<p class="headPlate"></p><p class="content"></p><p class="buttom"></p>')
                            $('.headPlate').html(e.data.headPlate)
                            $('.buttom').html(e.data.buttomPlate)
                            $('.content').html(e.data.graphicDetail)
                            if(e.data.headPlate==''&&e.data.graphicDetail==''&&e.data.buttomPlate==''){
                                $('.goods_content').append('<p style="text-align: center; font-size:20px; color:#999; line-height:100px;">暂无详情</p>')
                            }
                            // 添加自定义属性
                            if(e.data.customAttrList.length>'0'){
//                          	for(var cu=0;cu<e.data.customAttrList.length;cu++){
                                for(var cu in e.data.customAttrList){ 
                                    var customs=template(
                                        custom,{
                                            list:[{
//                                              name:e.data.customAttrList[cu].name,
												name:e.data.customAttrList[cu].name,
                                                value:e.data.customAttrList[cu].value
                                            }]
                                        }
                                    )
                                    $('.custom').append(customs)
                                }
                            }else{
	                            // 添加属性值  wuwq 2017-12-15 改
	                            var customTpl = $('#customTpl').html();
	                            if(e.data.attrList.length>'0'){
	                                for(var i=0;i<e.data.attrList.length;i++){
	                                    var customCont=template(
	                                        customTpl, {
	                                            customList: [{
	                                                name:e.data.attrList[i].name,
	                                                value:e.data.attrList[i].value
	                                           }]
	                                       }
	                                   );
	                                   $('.custom').append(customCont); 
	                                }
	                            }
                        	}
						}                            
                        else{
                            $('#left').append('<div>暂无推荐数据</div')
                            $('.none').hide();
                        }
                //categoryName
                // title
                if(e.data.categoryName!=''&&e.data.categoryName!=null){
                    var append_li=''
                    var tt=e.data.categoryName.split("&gt;")
                    
                    for (var a=0; a<tt.length;a++){
                        append_li+='<li><a class="search" target="_parent">'
                        append_li+=tt[a]
                        append_li+='</a>'
                        append_li+='>'
                        append_li+='</li>'  
                    }   
                    $('#category').append(append_li)
                    $('#category').append('<li class="dq"></li>')
                    $('.dq').append(e.data.name) 
                    $('.search').hover(function(){
                        var sea=$(this).text()
                        $('.search').attr('href','/src/search/search_list.html?keyword='+sea)
                    })
                }
                // 收藏数量
                if(e.data.isCollect == 1){
                    $('.social_fav').find('span').text('已收藏');
                    $('.social_fav .favcount').text('('+e.data.statisticsInfo.collectNum+'人气'+')');
                    $('.social_fav a').css('color','#baaa99');
                }
                // 人气
                $('.social_fav .favcount').text('('+e.data.statisticsInfo.collectNum+'人气'+')')  
                // 点击加入收藏
                $('.social_fav').click(function(){
                    var s=e.data.statisticsInfo.collectNum;
                    var goodsCommonId = e.data.commonId;
                    if($.cookie('user')!=''&&$.cookie('user')!=null){
                        strs=$.cookie('user').split(",")
                        var token=''
                        for(var i in strs){
                            token=strs[6]
                        }
                        var data={token:token,goodsCommonId:goodsCommonId}
                        $.ajax({
                            url:new_url+'shop/member_favorites/addGoodsFavorites',
                            type:'post',
                            data:data,
                            dataType:'json',
                            success:function(fav){
                                if(fav.code=='0'){
                                    tc(fav.message);
                                    s=s+1;
                                    $('.social_fav').find('span').text('已收藏');
                                    $('.social_fav .favcount').text('('+s+'人气'+')')
                                }else if(fav.code=='1'){
                                    tc(fav.message);
                                    $('.social_fav').find('span').text('已收藏')
                                    $('.social_fav .favcount').text('('+e.data.statisticsInfo.collectNum+'人气'+')');
                                }else{
                                    tc(fav.message);
                                }
                            }
                        })
                    }else{
                        // tc('请登录');
                        setTimeout(function(){
                            $('.popover_m, .site_bg').fadeIn()
                            $('.gb_01, .popover_m').click(function(){
                                $('.popover_m, .site_bg').fadeOut()
                            })
                        },200)
                    }
                })
                // 商品信息
                var t=template(
                    r_wrap_bg, {
                    list: [{
                            name:e.data.name,
                            advSlogan:e.data.advSlogan, 
                            price:e.data.price,
                            }]
                        }
                    );                                       
                    $('#r_wrap').append(t);
                    if(e.data.freight!='0.00'){
                        // 运费
                        $('.freight').text('￥'+e.data.freight).append('<em class="known">?<p class="known_text"></p></em>')
                        $('.known_text').append(e.data.freightInfo)
                    }
                    else{
                        $('.freight').text('免运费')
                    }
                    // code==4001 显示已下架
                    if(e.code=='4001'){ 
                        $('.btn_group').html('').append('<a style="width: 120px;height: 36px; border-radius: 4px;background: #e0e0e0; display: block; text-align: center;    line-height: 36px; font-size:14px;">商品已下架</a>')
                    }
                    // 商品轮播图
                    var img_src=''
                    for(var s_img=0; s_img<e.data.thumbList.length; s_img++){ 
                        var new_img=e.data.thumbList[s_img].split('!')[0] 
                            var str = e.data.thumbList[s_img]; 
                            var str1 = str.replace('dangmai', 'bgemall'); 
                        var w=template(
                            wrapper_bg,{
                                list:[{
                                    levelA:new_img+'!shop50',
                                }]
                            }
                        )
                        $('#wrapper').append(w)
                        // 默认显示第一张图片 选中第一个小图
                        $('#wrapper .item').eq(0).addClass('item-cur');
                        var im=$('#wrapper .item').eq(0).find('img').attr('src')
                        // 截取图片大小 自己设置合适的大小
                        var n_im=im.split('!')[0]
                        $('.small_box img').attr('src',n_im+'!shop800') 
                        $('.big_box img').attr('src',n_im+'!shop800')
                        // 鼠标hover选择图片
                        $('.item').hover(function(){
                            img_src=$(this).find('img').attr('src');
                            var new_im=img_src.split('!')[0] 
                            $(this).addClass('item-cur').siblings().removeClass('item-cur')
                            $('.small_box img').attr('src',new_im+'!shop800')
                            $('.big_box img').attr('src',new_im+'!shop800')      
                        })
                        // 左右点击移动
                        function left(){
                        $('#wrapper .item').each(function(index,t){                               
                            var w=parseInt($('#wrapper .item').css('width'));
                            var m=parseInt($('#wrapper .item').css('margin-right'))*2
                            var left=0 
                            $('#wrapper').css('width',(w+m)*(index+1)+2)
                            var z=(w+m)*(index+1)+2
                            var y=(w+m)*5 
                                $('.btn_next').click(function(){
                                    var m_l=parseInt($('#wrapper').css('margin-left')); 
                                    if(m_l>=-(z-y)){
                                        left+=w+m
                                        $('#wrapper').css('margin-left',-left).css('transition','all 0.3s')
                                    }
                                })
                                $('.btn_prev').click(function(){
                                    left=0
                                        $('#wrapper').css('margin-left',-left).css('transition','all 0.3s')
                                })
                        })
                    }left() 
                        
                    }  
                    // 获取商品全部价格 取最小-最大的价格 默认显示
                    var p=''
                    
                    for(var i=0;i<e.data.specGoodsList.length;i++){ 
                        p+=parseFloat(e.data.specGoodsList[i].unitPrice)+','
                    }
                    //排序 把价格从小到大显示
                    var arr =p.split(',');   
                    function sequence(a,b){
                        return a - b;
                    }
                    var arr1=arr.sort(sequence)               
                        for(var r=0; r<arr1.length; r++){
                            if(arr1[1]==arr1[r]){
                                // 只有一个价格区间 显示一个
                                $('.rnb').text('￥' + parseFloat(arr1[1]).toFixed(2))  
                            }
                            else{
                                
                                $('.rnb').text('￥' + parseFloat(arr1[1]).toFixed(2)+'  '+'-'+'  '+parseFloat(arr1[r]).toFixed(2))
                            }
                        }
                        
                // 有规格
                if(e.data.specList.length>'1'){
                        // 规格名称
                        $('.norms_color').text(e.data.specList[0].specName)
                        $('.norms_size').text(e.data.specList[1].specName)
                        // 商品规格 颜色 图片
                         for(var i=0; i<e.data.specList[0].valueList.length; i++){
                                var str = e.data.specList[0].valueList[i].image;
                                var str1 = str.replace('dangmai', 'bgemall');
                                var h=template(
                                    norms_bg, {
                                    list: [{
                                            valueName:e.data.specList[0].valueList[i].name,
                                            valueImg:str1,
                                            specId:e.data.specList[0].specId,
                                            valueId:e.data.specList[0].valueList[i].valueId
                                            }]
                                        }
                                );                                       
                                $('#norms').append(h);
                         }
                        //  尺码
                        if(e.data.specList.length>'1'){
                            for(var w=0; w<e.data.specList[1].valueList.length; w++){
                                var h_1=template(
                                    norms_spec_bg, {
                                    list: [{
                                            valueName:e.data.specList[1].valueList[w].name,
                                            specId:e.data.specList[1].specId,
                                            valueId:e.data.specList[1].valueList[w].valueId
                                            }]
                                        }
                                );                                       
                                $('#norms_spec').append(h_1);
                                    
                            }
                        }else{
                            $('#norms_spec').parent().hide();
                        }
                        
                        //  选择颜色出现规格判断是否有库存
                        //  颜色id
                        var color_spec=''
                        // 尺码id
                        var size_spec=''
                        //当前组合sku
                        var this_spec=''
                        // 全部sku组合
                        var sku=''
                        // goodsid
                        var goods_id=''
                        var th_sku=''
                        var th_sku2=''
                        var v=''
                        var m=''
                        var color=''
                        var size=''
                         $('.ify_yes span').click(function(){
                             $(this).addClass('active').siblings().removeClass('active');
                             color=$(this).attr('data-param')
                             if(e.data.specList.length>'1'){
                                $('.norms_hidden').show();
                             }
                             color_spec=$(this).attr('data-valueid')
                             $('.storage').text('') 
                             $('#goodsId').val('');
                             $('.ify_no span.active').click() 
                             this_sku()
                         })                      
                         $('.ify_no span').click(function(){
                            this_sku()
                            $(this).addClass('active').siblings().removeClass('active')
                            this_spec=$(this).attr('data-valueid')
                            size=$(this).attr('data-param')
                            $('#norms_label').text(color+'  '+size+'  ')
                            // 点击拼接sku组合 正序 或者反序
                            th_sku=color_spec+'|'+this_spec
                            th_sku2=this_spec+'|'+color_spec     
                             for(var i=0;i<e.data.specGoodsList.length;i++){
                                v=e.data.specGoodsList[i].combineSpec+':'+e.data.specGoodsList[i].storage
                                m=e.data.specGoodsList[i].combineSpec+':'+e.data.specGoodsList[i].unitPrice
                                goods_id=e.data.specGoodsList[i].combineSpec+':'+e.data.specGoodsList[i].goodsId 
                                if(e.data.specGoodsList[i].combineSpec==th_sku||e.data.specGoodsList[i].combineSpec==th_sku2){
                                    $('.storage').show().text('库存'+v.split(":")[1]+'件');  
                                    $('.rnb').text('￥'+m.split(":")[1])
                                    $('#goodsId').val(goods_id.split(":")[1]); 
                                }
                             }                        
                         })
                        //  数量加减
                        num=$('#goods_num').val()
                        $('.add').click(function(){
                            num++
                            $('#goods_num').val(num)
                            $('#norms_label').text(color+'  '+size+'  ') 
                            var text=$('.storage').text()
                            var k =parseInt(text.replace(/[^0-9]/ig,""));
                            if(num>k){
                                num =k
                                tc('库存不足')
                                $('#goods_num').val(num)
                                $('#norms_label').text(color+'  '+size+'  ')
                            }                      
                        })
                        $('.minus').click(function(){
                            num--
                            $('#goods_num').val(num)
                            $('#norms_label').text(color+'  '+size+'  ') 
                            if(num<1){
                                num = '1'
                                tc('最少购买数量为1件')
                                $('#goods_num').val(num)
                                $('#norms_label').text(color+'  '+size+'  ') 
                            }                         
                        })
                        function this_sku(){
                            // 获取全部sku组合
                           var z=e.data.specGoodsList
                            for(var i=0;i<z.length; i++){
                                 
                            //  获取规格id
                            $('.ify_no span').each(function(index,t){
                                size_spec+=$(t).attr('data-valueid')+'.'
                            })
                                // 分割字符串组成数组
                                //定义一数组 
                                var strs= new Array(); 
                                //字符分割 
                                strs=size_spec.split("."); 
                                for (y=0;y<(strs.length)-1 ;y++ ){                                    
                                    u=color_spec+"|"+strs[y]    
                                    if(z[i].combineSpec==u){
                                        if(z[i].storage.split(":")[0]=='0'){
                                                $('.ify_no .yes_click').each(function(){
                                                    if($(this).attr('data-valueid')==z[i].combineSpec.split("|")[1]){
                                                    $(this).hide();
                                                    if($(this).addClass('active')){
                                                        $(this).removeClass('active')
                                                    }
                                                };
                                            });
                                        }
                                        else{
                                            $('.ify_no .yes_click').each(function(){
                                            if($(this).attr('data-valueid')==z[i].combineSpec.split("|")[1]){
                                            $(this).show();
                                            };
                                            });
                                        }
                                    } 
                                }                                                       
                        }
                        } 
                        // 加入购物车 
                        $('.join_cart').click(function(){
                            if($.cookie('user')!=''&&$.cookie('user')!=null){
                                strs=$.cookie('user').split(",")
                                var token=''
                                for(var i in strs){
                                    token=strs[6]
                                }
                            if(!$('.ify_no .yes_click').hasClass('active')){
                                tc('请选择规格');
                                return false;
                            }else{
                                var this_goodsId=$('#goodsId').val()
                                var this_goods_num=$('#goods_num').val()
                                var goodsList='[{'+'"goodsId":'+this_goodsId+','+'"num":'+this_goods_num+'}]'
                                $.ajax({
                                    url:new_url+'shop/cart/addShopCart',
                                    type:'post',
                                    dataType:'json',
                                    data:{token:token,goodsList:goodsList},
                                    success:function(r){
                                        if(r.code=='0'){ 
                                            var freight=e.data.freight
                                            $.cookie('freight',freight,{path:'/'});
                                            tc(r.message)
                                            var img=$('.small_box img').attr('src')                      
                                            $('.small_box').append('<img class="goods_img">')
                                            $('.goods_img').attr('src',img).css({
                                                'position':'absolute',
                                                'width':'38px',
                                                'height':'38px',
                                            })
                                            setTimeout(function(){
                                                if(!$('.shopping_cart em').hasClass('red')){
                                                    $('.shopping_cart em').addClass('red')
                                                } 
                                               $('.goods_img').remove();

                                            },1200)
                                        }
                                        else{
                                            tc(r.message)
                                            $.cookie('user','',{path:''})
                                            setTimeout(function(){
                                                window.location.href='/src/login/login.html?type=2'
                                            },500)
                                            
                                        }
                                    }
                                })
                            }
                        }
                        else{
                            var img=$('.small_box img').attr('src')                            
                            $('.small_box').append('<img class="goods_img">')
                            $('.goods_img').attr('src',img).css({
                                'position':'absolute',
                                'width':'38px',
                                'height':'38px',
                            })
                            tc('加入成功')
                            setTimeout(function(){
                                if(!$('.shopping_cart em').hasClass('red')){
                                    $('.shopping_cart em').addClass('red')
                                } 
                               $('.goods_img').remove();
                               window.location.reload()
                            },1200)
                            var this_goodsId=$('#goodsId').val()
                            var this_goods_num=$('#goods_num').val()
                            var goodsList=''
                            goodsList='{'+'"goodsId":'+this_goodsId+','+'"num":'+this_goods_num+'}'
                            $.cookie('no_login',goodsList,{path:'/'}); 
                            if($.cookie('no_login')!=''){
                                goodsList= goodsList+'|'+new_arr
                                $.cookie('no_login',goodsList,{path:'/'});
                            }
                        }
                            return false
                        })
                        // 结算
                        $('.buy_now_btn').click(function(){
                            if($.cookie('user')!=''&&$.cookie('user')!=null){
                                strs=$.cookie('user').split(",")
                                var token=''
                                for(var i in strs){
                                    token=strs[6]
                                }
                            if(!$('.ify_no .yes_click').hasClass('active')){
                                tc('请选择规格');
                                return false;
                            }
                            else{
                                var buyNum= $('#goods_num').val()
                                var goodsId = $('#goodsId').val()
                                var isFromCart='0'
                                var goods_user=buyNum+'&'+goodsId+'&'+isFromCart
                                $.cookie('goods_user',goods_user,{path:'/'});
                                $.ajax({
                                    url:new_url+'shop/buy/getSettleGoodsList',
                                    data:{isFromCart:isFromCart,token:token,goodsId:goodsId,buyNum:buyNum},
                                    dataType:'json',
                                    type:'post',
                                    success:function(n){ 
                                            if(n.code!='0'){
                                                tc(n.message)
                                                if(e.data='1005'){
                                                    $.cookie('user','',{path:'/'})
                                                    setTimeout(function(){
                                                        window.location.href='/src/login/login.html?type=2'
                                                    },500)
                                                }
                                                return false;
                                            }
                                            else{
                                                tc(n.message)
                                                if($.cookie('my_cookie')!=null&&$.cookie('my_cookie')!=''){
                                                    $.cookie('my_cookie','',{path:'/'});
                                                }
                                                window.location.href='/src/cart/pay_commit.html' 
                                            }
                                    }
                                })
                            }
                        }
                        else{ 
                            setTimeout(function(){
                                $('.popover_m, .site_bg').fadeIn()
                                $('.gb_01, .popover_m').click(function(){
                                    $('.popover_m, .site_bg').fadeOut()
                                })
                            },200)
                        }
                        })
                    }




                    
                    // 没有规格
                    if(e.data.specList.length=='0'){
                        var sp=''
                        for(var i in e.data.specGoodsList){
                            sp =e.data.specGoodsList[i].storage 
                            $('.storage').show().text('库存'+e.data.specGoodsList[i].storage+'件')
                            $('.rnb').text('￥'+e.data.specGoodsList[i].unitPrice+'  ')
                        }
                        var sum =$('#goods_num').val()
                        $('#norms_label').text('默认'+'  ');
                        $('#norms').parent().hide();
                        //数量加减
                        $('.add').click(function(){
                            sum ++;
                            $('#goods_num').val(sum)
                            $('#norms_label').text('默认'+'  ') 
                            if(sum>=sp){
                                tc('库存不足')
                                sum=sp
                                $('#goods_num').val(sum)
                                $('#norms_label').text('默认'+'  ')
                            }
                        })
                        $('.minus').click(function(){
                            if(sum>1){
                                sum --;
                                $('#goods_num').val(sum)
                                $('#norms_label').text('默认'+'  ')
                            }
                            else{
                                tc('购买数量最少为1件')
                            }                                            
                        }) 
                        // 加入购物车
                        $('#goodsId').val(e.data.specGoodsList[i].goodsId) 
                        $('.join_cart').click(function(){
                            if($.cookie('user')!=''&&$.cookie('user')!=null){
                                strs=$.cookie('user').split(",")
                                var token=''
                                for(var i in strs){
                                    token=strs[6]
                                }   
                                var this_goodsId=$('#goodsId').val()
                                var this_goods_num=$('#goods_num').val()
                                var goodsList='[{'+'"goodsId":'+this_goodsId+','+'"num":'+this_goods_num+'}]'
                                $.ajax({
                                    url:new_url+'shop/cart/addShopCart',
                                    type:'post',
                                    dataType:'json',
                                    data:{token:token,goodsList:goodsList},                          
                                    success:function(r){ 
                                        if(r.code=='0'){
                                            var freight=e.data.freight
                                            $.cookie('freight',freight,{path:'/'});
                                            tc(r.message)
                                            var img=$('.small_box img').attr('src')                                       
                                            $('.small_box').append('<img class="goods_img">')
                                            $('.goods_img').attr('src',img).css({
                                                'position':'absolute',
                                                'width':'38px',
                                                'height':'38px',
                                            })
                                            setTimeout(function(){
                                                if(!$('.shopping_cart em').hasClass('red')){
                                                    $('.shopping_cart em').addClass('red')
                                                } 
                                               $('.goods_img').remove();

                                            },1200)
                                        }
                                        else{
                                            tc(r.message) 
                                            $.cookie('user','',{path:''})
                                            setTimeout(function(){
                                                window.location.href='/src/login/login.html?type=2'
                                            },500)
                                        }
                                    }
                                })
                        }
                        else{
                            // tc('请登录')
                            var img=$('.small_box img').attr('src') 
                            tc('加入成功')
                            $('.small_box').append('<img class="goods_img">')
                            $('.goods_img').attr('src',img).css({
                                'position':'absolute',
                                'width':'38px',
                                'height':'38px',
                            })
                            setTimeout(function(){
                                if(!$('.shopping_cart em').hasClass('red')){
                                    $('.shopping_cart em').addClass('red')
                                } 
                               $('.goods_img').remove();
                               window.location.reload()
                            },1200)
                            var this_goodsId=$('#goodsId').val()
                            var this_goods_num=$('#goods_num').val()
                            var goodsList=''
                            goodsList='{'+'"goodsId":'+this_goodsId+','+'"num":'+this_goods_num+'}' 
                            $.cookie('no_login',goodsList,{path:'/'});
                            if($.cookie('no_login')!=''){
                                goodsList= goodsList+'|'+new_arr
                                $.cookie('no_login',goodsList,{path:'/'});
                            }
                            
                        }                            
                        })
                        // 结算        
                        $('.buy_now_btn').click(function(){ 
                            if($.cookie('user')!=''&&$.cookie('user')!=null){
                                strs=$.cookie('user').split(",")
                                var token=''
                                for(var i in strs){
                                    token=strs[6]
                                }
                                var buyNum= $('#goods_num').val()
                                var goodsId = $('#goodsId').val()
                                var isFromCart='0'
                                var goods_user=buyNum+'&'+goodsId+'&'+isFromCart
                                $.cookie('goods_user',goods_user,{path:'/'});
                                $.ajax({
                                    url:new_url+'shop/buy/getSettleGoodsList',
                                    data:{isFromCart:isFromCart,token:token,goodsId:goodsId,buyNum:buyNum},
                                    dataType:'json',
                                    type:'post',
                                    success:function(n){ 
                                            if(n.code!='0'){
                                                tc(n.message)
                                                if(e.data='1005'){
                                                    $.cookie('user','',{path:'/'})
                                                    setTimeout(function(){
                                                        window.location.href='/src/login/login.html?type=2'
                                                    },500)
                                                }
                                                return false;
                                            }
                                            else{
                                                tc(n.message)
                                                if($.cookie('my_cookie')!=null&&$.cookie('my_cookie')!=''){
                                                    $.cookie('my_cookie','',{path:'/'});
                                                }
                                                window.location.href='/src/cart/pay_commit.html' 
                                            }

                                    }
                                })
                        }
                        else{
                            // tc('请登录')
                            setTimeout(function(){
                                $('.popover_m, .site_bg').fadeIn()
                                $('.gb_01, .popover_m').click(function(){
                                    $('.popover_m, .site_bg').fadeOut()
                                })
                            },200)
                        }                            
                        })              
                    }

                    //只有一个规格
                    if(e.data.specList.length=='1'){
                        // 颜色id
                        var color_spec=''
                        // 尺码id
                        var size_spec=''
                        //当前组合sku
                        var this_spec=''
                        // 全部sku组合
                        var sku=''
                        // goodsid
                        var goods_id=''
                        var th_sku=''
                        var th_sku2=''
                        var v=''
                        var m=''
                        var color=''
                        var size=''
                        $('.norms_color').text(e.data.specList[0].specName)
                        // 商品规格 颜色 图片
                         for(var i=0; i<e.data.specList[0].valueList.length; i++){
                                var str = e.data.specList[0].valueList[i].image;
                                var str1 = str.replace('dangmai', 'bgemall');
                                var h=template(
                                    norms_bg, {
                                    list: [{
                                            valueName:e.data.specList[0].valueList[i].name,
                                            valueImg:str1,
                                            specId:e.data.specList[0].specId,
                                            valueId:e.data.specList[0].valueList[i].valueId
                                            }]
                                        }
                                );                                       
                                $('#norms').append(h);
                                if(e.data.specList[0].valueList[i].image==''){
                                    var text=document.getElementsByClassName('yes_click')
                                    $('.yes_click').css({
                                        'height':'30px',
                                        'line-height':'30px',
                                        'margin-top':'7px',
                                        'text-align': 'center',
                                        'padding':'0 12px',
                                        'width':'auto'
                                    })
                                    $('.yes_click').find('img').remove();
                                    text[i].innerHTML=e.data.specList[0].valueList[i].name
                                }

                         }
                         
                         $('.ify_yes span').click(function(){
                            $(this).addClass('active').siblings().removeClass('active');
                            color=$(this).attr('data-param')
                            if(e.data.specList.length>'1'){
                                $('.norms_hidden').show();
                            }
                            this_spec=$(this).attr('data-valueid') 
                            $('.storage').text('')
                            $('#goodsId').val('');
                            $('#norms_label').text(color+'  ')
                            
                            for(var i=0;i<e.data.specGoodsList.length;i++){
                                v=e.data.specGoodsList[i].combineSpec+':'+e.data.specGoodsList[i].storage
                                m=e.data.specGoodsList[i].combineSpec+':'+e.data.specGoodsList[i].unitPrice
                                goods_id=e.data.specGoodsList[i].combineSpec+':'+e.data.specGoodsList[i].goodsId 
                                if(e.data.specGoodsList[i].combineSpec==this_spec){
                                    $('.storage').show().text('库存'+v.split(":")[1]+'件');  
                                    $('.rnb').text('￥'+m.split(":")[1])
                                    $('#goodsId').val(goods_id.split(":")[1]);
                                }
                             }  
                        })  
                           function this_sku(){
                                // 获取全部sku组合
                               var z=e.data.specGoodsList
                                for(var i=0;i<z.length; i++){
                                     
                                //  获取规格id
                                $('.ify_yes span').each(function(index,t){
                                    size_spec+=$(t).attr('data-valueid')+'.'
                                })
                                    // 分割字符串组成数组
                                    //定义一数组 
                                    var strs= new Array(); 
                                    //字符分割 
                                    strs=size_spec.split("."); 
                                    for (y=0;y<(strs.length)-1 ;y++ ){                                    
                                        u=strs[y]    
                                        if(z[i].combineSpec==u){
                                            if(z[i].storage.split(":")[0]=='0'){
                                            $('.ify_yes .yes_click').each(function(){
                                            if($(this).attr('data-valueid')==z[i].combineSpec){
                                            $(this).remove();
                                            };
                                                });
                                            }
                                        } 
                                    }                                                       
                            }
                        }this_sku() 

                        //  数量加减
                        num=$('#goods_num').val()
                        $('.add').click(function(){
                            num++
                            $('#goods_num').val(num)
                            $('#norms_label').text(color+'  ') 
                            var text=$('.storage').text()
                            var k =parseInt(text.replace(/[^0-9]/ig,""));
                            if(num>k){
                                num =k
                                tc('库存不足')
                                $('#goods_num').val(num)
                                $('#norms_label').text(color+'  ')
                            }                      
                        })
                        $('.minus').click(function(){
                            num--
                            $('#goods_num').val(num)
                            $('#norms_label').text(color+'  ') 
                            if(num<1){
                                num = '1'
                                tc('最少购买数量为1件')
                                $('#goods_num').val(num)
                                $('#norms_label').text(color+'  ') 
                            }                         
                        })
                        // 加入购物车 
                        $('.join_cart').click(function(){
                            if($.cookie('user')!=''&&$.cookie('user')!=null){
                                strs=$.cookie('user').split(",")
                                var token=''
                                for(var i in strs){
                                    token=strs[6]
                                }
                            if(!$('.ify_yes .yes_click').hasClass('active')){
                                tc('请选择规格');
                                return false;
                            }else{
                                var this_goodsId=$('#goodsId').val()
                                var this_goods_num=$('#goods_num').val()
                                var goodsList='[{'+'"goodsId":'+this_goodsId+','+'"num":'+this_goods_num+'}]'
                                $.ajax({
                                    url:new_url+'shop/cart/addShopCart',
                                    type:'post',
                                    dataType:'json',
                                    data:{token:token,goodsList:goodsList},
                                    success:function(r){
                                        if(r.code=='0'){
                                            var freight=e.data.freight
                                            $.cookie('freight',freight,{path:'/'});
                                            tc(r.message)
                                            var img=$('.small_box img').attr('src')                           
                                            $('.small_box').append('<img class="goods_img">')
                                            $('.goods_img').attr('src',img).css({
                                                'position':'absolute',
                                                'width':'38px',
                                                'height':'38px',
                                            })
                                            setTimeout(function(){
                                                if(!$('.shopping_cart em').hasClass('red')){
                                                    $('.shopping_cart em').addClass('red')
                                                } 
                                               $('.goods_img').remove();

                                            },1200)
                                        }
                                        else{
                                            tc(r.message)
                                            $.cookie('user','',{path:''})
                                            if(r.message==''){
                                                setTimeout(function(){
                                                    window.location.href='/src/login/login.html?type=2'
                                                },500)
                                            }
                                            
                                        }
                                    }
                                })
                            }
                        }
                        else{
                            // tc('请登录')
                            var img=$('.small_box img').attr('src') 
                            
                            $('.small_box').append('<img class="goods_img">')
                            $('.goods_img').attr('src',img).css({
                                'position':'absolute',
                                'width':'38px',
                                'height':'38px',
                            })
                            tc('加入成功')
                            setTimeout(function(){
                                if(!$('.shopping_cart em').hasClass('red')){
                                    $('.shopping_cart em').addClass('red')
                                } 
                               $('.goods_img').remove();
                               window.location.reload()
                            },1200)
                            var this_goodsId=$('#goodsId').val()
                            var this_goods_num=$('#goods_num').val()
                            var goodsList=''
                            goodsList='{'+'"goodsId":'+this_goodsId+','+'"num":'+this_goods_num+'}'
                            $.cookie('no_login',goodsList,{path:'/'}); 
                            if($.cookie('no_login')!=''){
                                goodsList= goodsList+'|'+new_arr
                                $.cookie('no_login',goodsList,{path:'/'});
                            }
                        }
                            return false
                        })
                        // 结算
                        $('.buy_now_btn').click(function(){
                            if($.cookie('user')!=''&&$.cookie('user')!=null){
                                strs=$.cookie('user').split(",")
                                var token=''
                                for(var i in strs){
                                    token=strs[6]
                                }
                            if(!$('.ify_yes .yes_click').hasClass('active')){
                                tc('请选择规格');
                                return false;
                            }
                            else{
                                var buyNum= $('#goods_num').val()
                                var goodsId = $('#goodsId').val()
                                var isFromCart='0'
                                var goods_user=buyNum+'&'+goodsId+'&'+isFromCart
                                $.cookie('goods_user',goods_user,{path:'/'});
                                $.ajax({
                                    url:new_url+'shop/buy/getSettleGoodsList',
                                    data:{isFromCart:isFromCart,token:token,goodsId:goodsId,buyNum:buyNum},
                                    dataType:'json',
                                    type:'post',
                                    success:function(n){ 
                                            if(n.code!='0'){
                                                tc(n.message)
                                                if(e.data='1005'){
                                                    $.cookie('user','',{path:'/'})
                                                    setTimeout(function(){
                                                        window.location.href='/src/login/login.html?type=2'
                                                    },500)
                                                }
                                                return false;
                                            }
                                            else{
                                                tc(n.message)
                                                if($.cookie('my_cookie')!=null&&$.cookie('my_cookie')!=''){
                                                    $.cookie('my_cookie','',{path:'/'});
                                                }
                                                window.location.href='/src/cart/pay_commit.html' 
                                            }

                                    }
                                })
                            }
                        }
                        else{
                            // tc('请登录')
                            setTimeout(function(){
                                $('.popover_m, .site_bg').fadeIn()
                                $('.gb_01, .popover_m').click(function(){
                                    $('.popover_m, .site_bg').fadeOut()
                                })
                            },200)
                        }
                        })
                    }
                    // 

            }
            else{
                tc(e.message)
            }
            
        }
    })
    // 商品详情tab切换
    $('.depict_wrap').hide().first().show();
    $('.top_tip li').eq(0).addClass('active')
    $('.top_tip li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
        $('.depict_wrap').hide()
        $('.depict_wrap').eq($(this).index()).show();  
    })        
     // 评价
            var url=window.location.search;
            var id = url.substring(url.lastIndexOf('=')+1, url.length);
            var pageNo='1'
            var evaluateType='';
            function p(){        
            $.ajax({
                url:new_url+'shop/goods/getGoodsEvaluate',
                type:'post',
                data:{goodsId:id,pageSize:'5'}, 
                dataType:'json',
                success:function(p){
                    var e_bg=$('#e_bg').html() 
                    $('.s1').text('全部评价('+p.data.totalNum+')')
                    if(p.data.evaluateList.length=='0'){
                        $('.evaluate_tip, .evaluate_top, .evaluate_list').css('display','none'); 
                        $('.goods_evaluate').append('<div style="width:245px;height:auto;margin:10px auto 30px;"><img src="../../img/base/icon_18.png" style="display:block;width:245px;height:127px;margin-bottom:30px;" /><p style="font-size:18px;color:#666;text-align:center;">本商品暂无评价</p></div>')
                    }
                    else{ 
                        var score=p.data.scoreNumbers.split(',') 
                        var red=document.getElementsByClassName('red1')
                        var evaluate_num=document.getElementsByClassName('evaluate_num')
                        for (var y=0; y<score.length; y++){
                            red[y].dataset.score=score[y]
                            red[y].style.width=(red[y].dataset.score/p.data.totalNum)*100+'%'
                            var h=parseInt(score[0])+parseInt(score[1])
                            var c=parseInt(score[4])
                            var z=parseInt(score[2])+parseInt(score[3])
                            $('.s2').text('好评('+h+')')
                            $('.s3').text('差评('+c+')')
                            $('.s4').text('中评('+z+')') 
                        }
                        //求平均分
                        //总评价数
                        var z_y=0
                        var z=p.data.totalNum
                        //总分数
                        $('.r_evaluate li').each(function(index,t){
                            var num1=parseInt($(t).find('.red1').attr('data-num'))
                            var scorenumbers=parseInt($(t).find('.red1').attr('data-score'))                          
                             z_y+=(num1*scorenumbers) 
                            $('.evaluate_num').text((z_y/z).toFixed(1))
                            $('.icon_start_j').css('width',+(z_y/z)*20+'%')
                        })

                        for(var i in p.data.evaluateList){ 
                            var time=p.data.evaluateList[i].createTime
                            function getLocalTime(nS) {     
                            return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); }
                            var memberName=p.data.evaluateList[i].memberName
                            if(p.data.evaluateList[i].isAnonymous=='1'){
                                var first_chr = memberName[0];
                                var last_chr = memberName[memberName.length-1];
                                if(memberName.length>'2'){
                                    memberName=first_chr+'*********'+last_chr
                                }
                                if(memberName.length=='2'){
                                    memberName=first_chr+'*'
                                }
                                if(memberName.length=='1'){
                                    memberName='*'
                                }
                            }
                            var evaluate=template(
                                e_bg,{
                                    list:[{
                                        memberId:p.data.evaluateList[i].evalId,
                                        memberName:memberName,
                                        scores:p.data.evaluateList[i].scores,
                                        content:p.data.evaluateList[i].content,
                                        member_avatar:p.data.evaluateList[i].memberAvatar,
                                        createTime:getLocalTime(time),
                                        isAnonymous:p.data.evaluateList[i].isAnonymous
                                    }]
                                }
                            )
                            $('#evaluate_list').append(evaluate) 
                            $('.evaluate_list li').each(function(){
                                if($(this).find('.evaluate_l img').attr('src')==''){
                                    $(this).find('.evaluate_l img').attr('src','../../img/base/member_msg_pic.png')
                                } 
                            }) 
                        } 
                        if(p.data.pageInfo.totalPages>'1'){
                            $('.more_bg').html('').append('<div id="more">加载更多页</div>')
                        }
                        function sco(){
                            $('.user_evaluate_star').each(function(index,t){
                                var scores= $(t).attr('data-scores');
                                if(scores=='1'){
                                    $(t).find('.icon_start').css({
                                        'width':'20%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='2'){
                                    $(t).find('.icon_start').css({
                                        'width':'40%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='3'){
                                    $(t).find('.icon_start').css({
                                        'width':'60%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='4'){
                                    $(t).find('.icon_start').css({
                                        'width':'80%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='5'){
                                    $(t).find('.icon_start').css({
                                        'width':'100%',
                                        'overflow':'hidden'
                                    })
                                }
                            })
                           }sco()  
                        // 加载分页
                        $('#more').click(function(){
                            pageNo++ 
                            $.ajax({
                                url:new_url+'shop/goods/getGoodsEvaluate',
                                type:'post',
                                data:{goodsId:id,pageSize:'5',pageNo:pageNo,}, 
                                dataType:'json',
                                success:function(p){
                                    var e_bg=$('#e_bg').html()
                                        for(var i in p.data.evaluateList){ 
                                            var time=p.data.evaluateList[i].createTime
                                            function getLocalTime(nS) {     
                                            return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); }
                                            var memberName=p.data.evaluateList[i].memberName
                                            if(p.data.evaluateList[i].isAnonymous=='1'){
                                                var first_chr = memberName[0];
                                                var last_chr = memberName[memberName.length-1];
                                                if(memberName.length>'2'){
                                                    memberName=first_chr+'*********'+last_chr
                                                }
                                                if(memberName.length=='2'){
                                                    memberName=first_chr+'*'
                                                }
                                                if(memberName.length=='1'){
                                                    memberName='*'
                                                }
                                            }
                                            var evaluate=template(
                                                e_bg,{
                                                    list:[{
                                                        memberId:p.data.evaluateList[i].evalId,
                                                        memberName:memberName,
                                                        scores:p.data.evaluateList[i].scores,
                                                        content:p.data.evaluateList[i].content,
                                                        member_avatar:p.data.evaluateList[i].memberAvatar,
                                                        createTime:getLocalTime(time),
                                                        isAnonymous:p.data.evaluateList[i].isAnonymous
                                                    }]
                                                }
                                            )
                                            $('#evaluate_list').append(evaluate) 
                                            $('.evaluate_list li').each(function(){
                                                if($(this).find('.evaluate_l img').attr('src')==''){
                                                    $(this).find('.evaluate_l img').attr('src','../../img/base/member_msg_pic.png')
                                                } 
                                            })
                                        } 
                                        sco() 
                                        if(p.data.pageInfo.totalPages<=pageNo){
                                            $('#more').text('没有更多了')
                                        }
                                    } 
                        })            
                        })                 
                    } 
                }
        })
    }p()
        // 评价切换
        $('.evaluate_tip_2 span').click(function(){
            $('#more').remove();
            pageNo='1'
            evaluateType=$(this).attr('data-evaluatetype')
            $(this).addClass('active').siblings().removeClass('active');
            $('#evaluate_list').html('').append('<p class="none">加载中....</p>') 
            $.ajax({
                url:new_url+'shop/goods/getGoodsEvaluate',
                type:'post',
                data:{goodsId:id,pageSize:'5',evaluateType:evaluateType}, 
                dataType:'json',
                success:function(p){
                    var e_bg=$('#e_bg').html()
                    if(p.data.evaluateList.length=='0'){
                        $('#evaluate_list').append('<li style="text-align: center; font-size:20px; color:#999; line-height:100px;">暂无评价</li>') 
                        $('.none').remove();
                    }                   
                    else{ 
                        for(var i in p.data.evaluateList){ 
                            var time=p.data.evaluateList[i].createTime
                            function getLocalTime(nS) {     
                            return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); }
                            var memberName=p.data.evaluateList[i].memberName
                            if(p.data.evaluateList[i].isAnonymous=='1'){
                                var first_chr = memberName[0];
                                var last_chr = memberName[memberName.length-1];
                                if(memberName.length>'2'){
                                    memberName=first_chr+'*********'+last_chr
                                }
                                if(memberName.length=='2'){
                                    memberName=first_chr+'*'
                                }
                                if(memberName.length=='1'){
                                    memberName='*'
                                }
                            }
                            var evaluate=template(
                                e_bg,{
                                    list:[{
                                        memberId:p.data.evaluateList[i].evalId,
                                        memberName:memberName,
                                        scores:p.data.evaluateList[i].scores,
                                        content:p.data.evaluateList[i].content,
                                        member_avatar:p.data.evaluateList[i].memberAvatar,
                                        createTime:getLocalTime(time),
                                        isAnonymous:p.data.evaluateList[i].isAnonymous
                                    }]
                                }
                            )
                            $('#evaluate_list').append(evaluate) 
                            $('.none').remove();
                            $('.evaluate_list li').each(function(){
                                if($(this).find('.evaluate_l img').attr('src')==''){
                                    $(this).find('.evaluate_l img').attr('src','../../img/base/member_msg_pic.png')
                                } 
                            })
                        } 
                        if(p.data.pageInfo.totalPages>'1'){
                            $('.more_bg').html('').append('<div id="more">加载更多页</div>')
                        }
                        function sco(){
                            $('.user_evaluate_star').each(function(index,t){
                                var scores= $(t).attr('data-scores');
                                if(scores=='1'){
                                    $(t).find('.icon_start').css({
                                        'width':'20%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='2'){
                                    $(t).find('.icon_start').css({
                                        'width':'40%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='3'){
                                    $(t).find('.icon_start').css({
                                        'width':'60%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='4'){
                                    $(t).find('.icon_start').css({
                                        'width':'80%',
                                        'overflow':'hidden'
                                    })
                                }
                                if(scores=='5'){
                                    $(t).find('.icon_start').css({
                                        'width':'100%',
                                        'overflow':'hidden'
                                    })
                                }
                            })
                           }sco()  
                        // 加载分页
                        $('#more').click(function(){
                            pageNo++ 
                            $.ajax({
                                url:new_url+'shop/goods/getGoodsEvaluate',
                                type:'post',
                                data:{goodsId:id,pageSize:'5',pageNo:pageNo,}, 
                                dataType:'json',
                                success:function(p){
                                    var e_bg=$('#e_bg').html()
                                        for(var i in p.data.evaluateList){ 
                                            var time=p.data.evaluateList[i].createTime
                                            function getLocalTime(nS) {     
                                            return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); }
                                            var memberName=p.data.evaluateList[i].memberName
                                            if(p.data.evaluateList[i].isAnonymous=='1'){
                                                var first_chr = memberName[0];
                                                var last_chr = memberName[memberName.length-1];
                                                if(memberName.length>'2'){
                                                    memberName=first_chr+'*********'+last_chr
                                                }
                                                if(memberName.length=='2'){
                                                    memberName=first_chr+'*'
                                                }
                                                if(memberName.length=='1'){
                                                    memberName='*'
                                                }
                                            }
                                            var evaluate=template(
                                                e_bg,{
                                                    list:[{
                                                        memberId:p.data.evaluateList[i].evalId,
                                                        memberName:memberName,
                                                        scores:p.data.evaluateList[i].scores,
                                                        content:p.data.evaluateList[i].content,
                                                        member_avatar:p.data.evaluateList[i].memberAvatar,
                                                        createTime:getLocalTime(time),
                                                        isAnonymous:p.data.evaluateList[i].isAnonymous
                                                    }]
                                                }
                                            )
                                            $('#evaluate_list').append(evaluate) 
                                            $('.evaluate_list li').each(function(){
                                                if($(this).find('.evaluate_l img').attr('src')==''){
                                                    $(this).find('.evaluate_l img').attr('src','../../img/base/member_msg_pic.png')
                                                } 
                                            })
                                        } 
                                        sco() 
                                        if(p.data.pageInfo.totalPages<=pageNo){
                                            $('#more').text('没有更多了')
                                        }
                                    } 
                        })            
                        })                 
                    } 
                }
        })
        }) 
})